package com.adcc.loadsheet.billing.security;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.util.MD5Util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 将json的登录请求转为spingsecurity认可的登录模式
 * Created by zhaoml on 2020-04-01.
 */
public class PreLogonFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)
                || request.getContentType().equals("application/json;charset=utf-8")) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()) {
                Map<String,String> authenticationBean = mapper.readValue(is, Map.class);
                if(Strings.isNullOrEmpty(authenticationBean.get("username")) || Strings.isNullOrEmpty(authenticationBean.get("password"))){
                    //抛异常
                    throw new IOException("参数异常");
                }
                boolean isCorrect=false;
                for(Cookie one :request.getCookies()){
                    if("validateCode".equals(one.getName())&&one.getValue().equals(MD5Util.StringMD5(authenticationBean.get("verifycode")))){
                        isCorrect=true;
                        break;
                    }
                }
                if(!isCorrect){
                    throw new UsernameNotFoundException("验证码错误！");
                }
//                Log.info("verifycode输入验证码："+authenticationBean.get("verifycode"));
//                Log.info("validateCode正确验证码："+request.getSession().getAttribute("validateCode"));
//                if(request.getSession().getAttribute("validateCode")==null||!request.getSession().getAttribute("validateCode").equals(authenticationBean.get("verifycode"))){
//                    throw new UsernameNotFoundException("验证码错误！");
//                }
                authRequest = new UsernamePasswordAuthenticationToken(
                        authenticationBean.get("username"), authenticationBean.get("password"));
            } catch (IOException e) {
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            }
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        else {
            return super.attemptAuthentication(request, response);
        }
    }
}